<?php
function crown_preprocess_node(&$vars) {
  $node = $vars["node"];  //print_r($vars);exit;
  //if ($node->type=='scheduled-report') {
    $vars['submitted'] = t('Submitted by: !username on !datetime', array('!username' => $vars['name'], '!datetime' => $vars['date']));
  //

  if($node->type=='scheduled_report') {
    isset($vars['content']['field_uploaded']['#title']) && $vars['content']['field_uploaded']['#title'] = t('Upload');
    isset($vars['content']['field_date']['#title']) && $vars['content']['field_date']['#title'] = t('Report Date');
    //unset($vars['content']['field_date'][0]);
    $timestamp = isset($vars['content']['field_date']['#items']['0']['value']) ? $vars['content']['field_date']['#items']['0']['value'] : '';
    $format = 'M Y';
    $output = format_date($timestamp, 'custom', $format);
    $vars['content']['field_date'][0]['#markup'] = '<span class="date-display-single" property="dc:date" datatype="xsd:dateTime" content="">'.$output.'</span>';
  }
}

function crown_preprocess_page(&$vars) {
  drupal_add_js(drupal_get_path('module', 'webformview') . '/js/webform_language.js');
  // the web information id
  $webinfo_id = defined('WEB_ID') ? WEB_ID : '' ; 
  $meta_webinfo = array(
    '#type' => 'html_tag',
    '#tag' => 'meta',
    '#attributes' => array(
        'name' => 'webinfo',
        'content' => $webinfo_id
    )
   );
  drupal_add_html_head( $meta_webinfo, 'meta_webinfo' );
  
  // Set the title for diffient contry
  if( isset($vars['node']->nid) && $vars['node']->nid ){
    $initiation_result = webform_get_initiation_title($vars['node']->nid);
    if(isset($initiation_result['if_initiation']) && $initiation_result['if_initiation'] ){
      drupal_set_title($initiation_result['initiation_title']);
      //add one hidden field for js to justify whether it s initiation form
    }
  }
  
  //  The tab name for "New Initiation" should be "New"
  $initiation_form_arr = array(
      "node/" . PG_INITIATION_FORM_NID,
      "node/" . PG_IF_JAP,
      "node/" . PG_IF_TUR,
      "node/" . PG_IF_MEX,
      "node/" . PG_IF_AU,
  );
  if (isset($vars['tabs']['#primary']) && is_array($vars['tabs']['#primary'])) {
    foreach ($vars['tabs']['#primary'] as &$value) {
      if (in_array($value['#link']['href'], $initiation_form_arr) && $value['#link']['title'] == t('View')) {
        $value['#link']['title'] = t('New');
        if (isset($_REQUEST['country']) && !empty($_REQUEST['country'])) {
          global $base_url;
          $value['#link']['href'] = $base_url . '/' . $value['#link']['href'] . '?country=' . $_REQUEST['country'];
          $value['#link']['external'] = TRUE;
        }
        break;
      }
      
    }
  }
  //  Change the tab  "Results" link
  $initiation_form_arr = array(
      "node/" . PG_INITIATION_FORM_NID . '/webform-results',
      "node/" . PG_IF_JAP . '/webform-results',
      "node/" . PG_IF_TUR . '/webform-results',
      "node/" . PG_IF_MEX . '/webform-results',
      "node/" . PG_IF_AU . '/webform-results',
  );
  if (isset($vars['tabs']['#primary']) && is_array($vars['tabs']['#primary'])) {
    foreach ($vars['tabs']['#primary'] as &$value) {
      if (in_array($value['#link']['href'], $initiation_form_arr) && $value['#link']['title'] == t('Results')) {
        if (isset($_REQUEST['country']) && !empty($_REQUEST['country'])) {
          global $base_url;
          $value['#link']['href'] = $base_url . '/' . $value['#link']['href'] . '?country=' . $_REQUEST['country'];
          $value['#link']['external'] = TRUE;
        }
        break;
      }
    }
  }
  //  Change the tab  "Cancelled" link
  $initiation_form_arr = array(
      "node/" . PG_INITIATION_FORM_NID . '/webform-cancelled',
      "node/" . PG_IF_JAP . '/webform-cancelled',
      "node/" . PG_IF_TUR . '/webform-cancelled',
      "node/" . PG_IF_MEX . '/webform-cancelled',
      "node/" . PG_IF_AU . '/webform-cancelled',
  );
  if (isset($vars['tabs']['#primary']) && is_array($vars['tabs']['#primary'])) {
    foreach ($vars['tabs']['#primary'] as &$value) {
      if (in_array($value['#link']['href'], $initiation_form_arr) && $value['#link']['title'] == t('Cancelled Initiations')) {
        if (isset($_REQUEST['country']) && !empty($_REQUEST['country'])) {
          global $base_url;
          $value['#link']['href'] = $base_url . '/' . $value['#link']['href'] . '?country=' . $_REQUEST['country'];
          $value['#link']['external'] = TRUE;
        }
        break;
      }
      //taxonomy/term/
      if(strpos($value['#link']['href'], 'taxonomy/term/') !== FALSE){
        global $base_url;
        $value['#link']['href'] = $base_url . '/' . $value['#link']['href'].'?destination='.$_GET['destination'];
        $value['#link']['external'] = TRUE;
      }
      //node/[nid]
      if (strpos($value['#link']['href'], 'node/') !== FALSE) {
        global $base_url;
        $nid = (int) arg(1);
        if ($nid) {
          $node = node_load($nid);
          if ($node->type != 'webform') {
            if(isset($_GET['destination'])){
              $value['#link']['href'] = $base_url . '/' . $value['#link']['href'] . '?destination=' . $_GET['destination'];
              $value['#link']['external'] = TRUE;
            }
          }
        }
      }
    }
  }
  
  
  
  
  
  
  // Move secondary tabs into a separate variable.
  $vars['tabs2'] = array(
      '#theme' => 'menu_local_tasks',
      '#secondary' => $vars['tabs']['#secondary'],
  );
  unset($vars['tabs']['#secondary']);
  // Set a variable for the site name title and logo alt attributes text.
  $slogan_text = $vars['site_slogan'];
  $site_name_text = $vars['site_name'];
  $vars['site_name_and_slogan'] = $site_name_text . ' ' . $slogan_text;
  if((arg(0)== 'services' && $_GET['api'] == 'getlayout') || arg(0) == 'ajaxlogin'){
    unset($vars['page']['header_bottom']);
  }

  //output login bar
  global $user;
  $links = array();
  if ($user->uid) {
    $links = array(
        'account' => array(
            'title' => t('<strong>@username</strong>', array('@username' => format_username($user))),
            'href' => 'user',
            'html' => TRUE,
            'attributes' => array('title' => t('User account')),
        ),
        'logout' => array(
            'title' => t('Logout'),
            'href' => 'caslogout',
        ),
    );
  }
  else {
    /*$links = array(
        'login' => array(
            'title' => t('Log in'),
            'href' => 'user',
        ),
    );*/
  }
  $vars['login_bar'] = theme('links', array('links' => $links));
  //bind logout event
  $logout_api = variable_get('BB_ST_NET_REPORT_LOGOUT_API');
  $logout_event = <<< EOT
 jQuery(document).ready(function(){
      jQuery(".login-bar .logout").click(function(){
         jQuery.getScript("$logout_api",function(){});
       }   
     );
  });
EOT;
  drupal_add_js($logout_event,'inline');
  if((isset($_SESSION['pg_refer_anonymous']) && $_SESSION['pg_refer_anonymous']) || (isset($_SESSION['special_init2']) && $_SESSION['special_init2'])){
    //$vars['page']['header'] = '';
    unset($vars['page']['header']);
    //if($_SESSION['no_language_selection']){
      //$vars['page']['header_bottom'] = '';
    //}
    //$vars['page']['right'] = '';
    $vars['page']['footer'] = '';
    $vars['login_bar'] = TRUE;
    //if(arg(3) != md5(variable_get('BB_ST_CURRENT_CROP_ID','AFE3D845C4B4D357482566FA00131FBE'))){
      //$vars['page']['content']= t('Access Denied');
    //}
    $vars['logo'] = '';
  }
  
  //remove side bar & menu
  if(arg(0) == 'noaccess'){
    unset($vars['page']['header_bottom']['system_user-menu']);
    unset($vars['page']['right']);
  }
  global $user;
  if( array_intersect($user->roles, array('ADMIN_BUS','ADMIN_IT')) && !in_array('administrator',$user->roles) ){

    if (arg(0) == 'admin' && arg(1) == 'people' && !arg(2)){
      drupal_goto('admin/people/create');
    }
  }
  //change admin content title
  if(arg(0) == 'admin' && arg(1) == 'content'){
    drupal_set_title(t('Content Management'));
  }
  if(arg(0) == 'admin' && arg(1)=='people' && arg(2) == 'permissions'){
    drupal_set_title(t('Role Configuration'));
  }
  
  
  if (arg(0) == 'usermanage' && arg(1) == 'forget' && !arg(2)){
    $vars['page']['crownlogo'] = '<div id="usermange-forget-sidebar"><div class="bottom_logo">CROWN</div></div>';
  }
  elseif (arg(0) == 'empty' && !arg(1)){
    $vars['page']['crownlogo'] = '<div id="usermange-forget-sidebar"><div class="bottom_logo">CROWN</div></div>';
  }
  //processs admin/structure/taxonomy
  if(strpos($_GET['q'],'admin/structure/taxonomy') !== FALSE){
    if(isset($vars['tabs'])){
      $vars['tabs'] = NULL;
    }
    if(isset($vars['action_links'][0]['#link'])){
      if($vars['action_links'][0]['#link']['title'] == 'Add term'){
        $vars['action_links'][0]['#link']['title'] = 'Add Category';
      }
    }
  }
  
}

function crown_pager($variables) {
  $tags = $variables['tags'];
  $element = $variables['element'];
  $parameters = $variables['parameters'];
  $quantity = $variables['quantity'];
  global $pager_page_array, $pager_total;

  // Calculate various markers within this pager piece:
  // Middle is used to "center" pages around the current page.
  $pager_middle = ceil($quantity / 2);
  // current is the page we are currently paged to
  $pager_current = $pager_page_array[$element] + 1;
  // first is the first page listed by this pager piece (re quantity)
  $pager_first = $pager_current - $pager_middle + 1;
  // last is the last page listed by this pager piece (re quantity)
  $pager_last = $pager_current + $quantity - $pager_middle;
  // max is the maximum page number
  $pager_max = $pager_total[$element];
  // End of marker calculations.

  // Prepare for generation loop.
  $i = $pager_first;
  if ($pager_last > $pager_max) {
    // Adjust "center" if at end of query.
    $i = $i + ($pager_max - $pager_last);
    $pager_last = $pager_max;
  }
  if ($i <= 0) {
    // Adjust "center" if at start of query.
    $pager_last = $pager_last + (1 - $i);
    $i = 1;
  }
  // End of generation loop preparation.

  $li_first = theme('pager_first', array('text' => (isset($tags[0]) ? $tags[0] : t('« First')), 'element' => $element, 'parameters' => $parameters));
  $li_previous = theme('pager_previous', array('text' => (isset($tags[1]) ? $tags[1] : t('‹ Previous')), 'element' => $element, 'interval' => 1, 'parameters' => $parameters));
  $li_next = theme('pager_next', array('text' => (isset($tags[3]) ? $tags[3] : t('Next ›')), 'element' => $element, 'interval' => 1, 'parameters' => $parameters));
  $li_last = theme('pager_last', array('text' => (isset($tags[4]) ? $tags[4] : t('Last »')), 'element' => $element, 'parameters' => $parameters));

  if ($pager_total[$element] > 1) {
    if ($li_first) {
      $items[] = array(
        'class' => array('pager-first'),
        'data' => $li_first,
      );
    }
    if ($li_previous) {
      $items[] = array(
        'class' => array('pager-previous'),
        'data' => $li_previous,
      );
    }

    // When there is more than one page, create the pager list.
    if ($i != $pager_max) {
      if ($i > 1) {
        $items[] = array(
          'class' => array('pager-ellipsis'),
          'data' => '…',
        );
      }
      // Now generate the actual pager piece.
      for (; $i <= $pager_last && $i <= $pager_max; $i++) {
        if ($i < $pager_current) {
          $items[] = array(
            'class' => array('pager-item'),
            'data' => theme('pager_previous', array('text' => $i, 'element' => $element, 'interval' => ($pager_current - $i), 'parameters' => $parameters)),
          );
        }
        if ($i == $pager_current) {
          $items[] = array(
            'class' => array('pager-current'),
            'data' => $i,
          );
        }
        if ($i > $pager_current) {
          $items[] = array(
            'class' => array('pager-item'),
            'data' => theme('pager_next', array('text' => $i, 'element' => $element, 'interval' => ($i - $pager_current), 'parameters' => $parameters)),
          );
        }
      }
      if ($i < $pager_max) {
        $items[] = array(
          'class' => array('pager-ellipsis'),
          'data' => '…',
        );
      }
    }
    // End generation.
    if ($li_next) {
      $items[] = array(
        'class' => array('pager-next'),
        'data' => $li_next,
      );
    }
    if ($li_last) {
      $items[] = array(
        'class' => array('pager-last'),
        'data' => $li_last,
      );
    }
    return '<h2 class="element-invisible">' . t('Pages') . '</h2>' . theme('item_list', array(
      'items' => $items,
      'attributes' => array('class' => array('pager')),
    ));
  }
}


function crown_preprocess_username(&$variables){
  $if_initiation = FALSE;
  $nid = arg(1);
  $country_arr = webform_get_country($nid);
  if(isset($country_arr['key']) && $country_arr['key']){
    $if_initiation = TRUE;
  }
  
  if(arg(0) == 'node' && $if_initiation && ( arg(2) == 'submission' || arg(2) == 'cancelled' )){
    $variables['name'] = check_plain($variables['account']->name);
  }
}